import Reflux from 'reflux';
import PageConst from './PageConst';
import Actions from './Actions';
import Utils from './../../../utils';
import { Control } from 'react-keeper';
import update from 'react-addons-update';
import moment from 'moment';
import StorageUtils from '../../../app/storage';
import DB from './../../../app/db';
const { API_URL} = require(`./../../../config/${ENV}.json`);

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    ...PageConst,
    //操作类型
    operType: 'add',
    //操作类型
    isNew : true,

    //数据主键ID
    spId: '',
    //是否锁定
    readOnly: false,

    //是否上传
    isUpload: false,
    //选中的工程
    currentEng: {},
    jdy:[],
    files: [],
    urls:[],
    mediaId:[],
    steps: [],
    area:"",
    //保存成功弹出提示
    showToptips: false,
    gallery: false,
    galleryIndex: '',
    editable:true,
    showWarn: false,
    warnTimer: null,
    codeTimer: null,
    warnMessage: '',
    currentStep:10,
    userInfo: {
      certNum: '',
      telNum: '',
      vcode: '',
      name:'',
      organName:''
    },
  },

  initMode: function () {
    let t = this;
    t.data.operType == 'add';
    this.data.userInfo = update(this.data.userInfo, {$merge: {...StorageUtils.getStorage().get('user')}});
    this.data.editable = update(this.data.editable, {$set: true});
    this.data.files =  update(this.data.files,  {$set: []});
    this.data.urls = update(this.data.urls, {$set: []});
    this.data.mediaId = update(this.data.mediaId, {$set: []});
    this.data.gallery = update(this.data.gallery, {$set: false});
    this.data.jlmode = update(this.data.jlmode,  {$set: {}});
  if (!__LOCAL__) {

    this.data.jlmode.jlr = update(this.data.jlmode.jlr,  {$set: this.data.userInfo.telNum});
    this.data.jlmode.creatorId = update(this.data.jlmode.creatorId,  {$set: this.data.userInfo.telNum});
  }
  else
  {
    this.data.jlmode.jlr = update(this.data.jlmode.jlr,  {$set: '13972608122'});
    this.data.jlmode.creatorId = update(this.data.jlmode.creatorId,  {$set: '13972608122'});
  }
    this.data.jlmode.router = update(this.data.jlmode.router,  {$set: '/myyewu/shenbaozlzghf'});
    this.data.jlmode.jllxName = update(this.data.jlmode.jllxName,  {$set: '整改回复'});
    this.data.jlmode.shzt = update(this.data.jlmode.shzt,  {$set: ''});
    this.data.jlmode.jllx = update(this.data.jlmode.jllx,  {$set: '0033'});
    this.data.jlmode.glJdjlId = update(this.data.jlmode.glJdjlId,  {$set: ''});
    this.data.isNew = update(this.data.isNew,  {$set: true});
    this.data.isUpload = update(this.data.isUpload,  {$set: false});
    this.data.currentEng =  update(this.data.currentEng,  {$set: {}});
    this.data.jlmode.jdy =  update(this.data.jlmode.jdy,  {$set: []});
    this.data.jdy =  update(this.data.jdy,  {$set: []});
    var jlrq = new Date();
    this.data.jlmode.jlrq = update(this.data.jlmode.jlrq,  {$set: jlrq.getTime()});


    t.updateComponent();
  },

  loadJLGlId: function (params) {
    let t = this;
    params.keyword = this.data.gljl.id;
    if (!__LOCAL__) {
      params.userid = this.data.userInfo.telNum;
    }
    this.data.jlmode.glJdjlId = update(this.data.jlmode.glJdjlId,  {$set: this.data.gljl.id});

    DB.WechatAPI.findZGHFControlGl(params).then(
      function (content) {
        if (content != null) {
          if (content.content != null) {
            if (content.content.length > 0) {
              t.data.jlmode = update(t.data.jlmode, {$set: content.content[0]});
              console.info(t.data.jlmode);
              t.data.operType = update(t.data.operType,  {$set: 'update'});
              t.data.isNew = update(t.data.isNew,  {$set: false});
              t.data.isUpload = update(t.data.isUpload, {$set: t.data.jlmode.isUpload});
              t.data.readOnly = false;

              Actions.loadImgFile({'spId':t.data.jlmode.id});
              t.updateComponent();
            }
          }
        }
      },
      function (error) {
        console.log(error);
      });

  },




  loadMode: function (params) {
    let t = this;
    this.data.gljl =  update(this.data.gljl,  {$set: params});
    this.loadJLGlId({
      page: 1,
      size: 1,
      keyword:'',
      userid:'13972608122',
      engid:'',
      rq:'',
    });
    this.loadEng({'engId' :this.data.gljl.engId});
    this.initStep();
    this.loadStep();
    t.updateComponent();
  },

  loadEng: function (obj) {
    let t = this;


    if (obj != '')
    {
      DB.WechatAPI.getEngById({'code':obj.engId}).then(
        function (content) {
          t.data.currentEng =  update(t.data.currentEng,  {$set: content});
          t.data.jlmode = update(t.data.jlmode,{eng : {$set: t.data.currentEng}}  );
          t.updateComponent();
        },
        function (error) {
          console.log(error);
        });
    }
  },

  initStep: function () {
    let t = this;
    console.info('步骤111111111');
    t.data.steps =  update(t.data.steps,  {$set: []});
    this.data.shstep.forEach(function(value,index,array){
      t.data.steps.push({
        title:value.title,
        description: value.description,
      })

    });

    console.info(this.data.currentStep);
    this.updateComponent();

  },

  loadStep: function () {
    let t = this;

    console.info('步骤222222');
    console.info(this.data.jlmode.shzt);
    /*this.data.pdata.shzt =  update(this.data.pdata.shzt,  {$set: '123'});*/
    switch(this.data.jlmode.shzt){
      case "审核通过" :
        this.onStepThree();
        t.data.currentStep =  update(t.data.currentStep,  {$set: 2});
        break;
      case "签发（审核）通过" :
        this.onStepThree();
        t.data.currentStep =  update(t.data.currentStep,  {$set: 2});
        break;
      case "" :
        this.onStepOne();
        t.data.currentStep =  update(t.data.currentStep,  {$set: 0});
        break;
      default :
        this.onStepTwo();
        t.data.currentStep =  update(t.data.currentStep,  {$set: 1});
        ; break;
    }

    t.updateComponent();

  },

  onStepOne: function () {
    this.data.steps.forEach(function(value,index,array){
      if(value.title==='填报')
      {
        value.description='运行中';
      }
    });
    this.updateComponent();
  },


  onStepTwo: function () {
    this.data.steps.forEach(function(value,index,array){
      if(value.title==='审核')
      {
        value.description='运行中';
      }
      if(value.title==='填报')
      {
        value.description='已完成';
      }
    });
    this.updateComponent();
  },

  onStepThree: function () {
    this.data.steps.forEach(function(value,index,array){
      value.description='已完成';
    });
    this.updateComponent();
  },

  onShowFiles: function (index) {
    this.data.gallery = update(this.data.gallery, {$set: true});
    this.data.galleryIndex = update(this.data.galleryIndex, {$set: index});

    if(this.data.editable){
      this.data.urls = update(this.data.urls, {$set: []});
      this.data.urls = update(this.data.urls, {
        $apply: (urls) => {
          return this.data.files.map((v, i) => {
            return urls.concat(v.url);
          })
        }
      })
    }
    this.updateComponent();

  },


  clickFiles: function (fileobj,i) {
    this.data.gallery = update(this.data.gallery, {$set: { url: fileobj.url,id:i}});
    this.updateComponent();
  },

  onSaveImgFile: function (params) {
    let t = this;
    console.info("图片");
    console.info(this.data.jlmode.id);
    console.info(this.data.mediaId);
    this.pa
    DB.WechatAPI.saveImgFileUrl({'glid':this.data.jlmode.id, 'ids':this.data.mediaId}).then(
      function (content) {
        if (null != content ) {
          if(content.length>0){
            t.updateComponent();
          }
        }
      },
      function (error) {
        console.log(error);
      });
  },

  onLoadImgFile: function (params) {
    let t = this;
    DB.WechatAPI.getImgFileUrl(params).then(
      function (content) {
        if (null != content ) {

          var urlsxiao=[];
          if(content.length>0){

            for(var i=0;i<content.length;i++){
              var url=API_URL+content[i].httpurl;
              urlsxiao.push({'url':url,'code':content[i].id});
              t.data.mediaId.push(content[i].id);
            }
            t.data.urls=update(t.data.urls,  {$set: urlsxiao});
            t.updateComponent();
            console.info("urls");
            console.info(t.data.urls);
          }
        }

      },
      function (error) {
        console.log(error);
      });
  },

  onImgUrlFile: function (obj) {
    let t = this;
    t.data.urls.push({'url':API_URL+obj.data.httpurl,'code':obj.data.id});

  },

  onAddFiles: function (fileobj,wcmv,pageobj) {
    pageobj.showLoading();
    var t=this;

    DB.WechatAPI.uploadMedia(wcmv).then(
      function (content) {
        console.info('增加返回a');
        console.info(content);
        if(null!=content){
          t.data.mediaId.push(content.data.id);
/*          t.data.files = update(t.data.files, {
            $apply: (files) => {
              return files.concat(update(fileobj, {$merge: {url: fileobj.data}}));
            }
          })*/
          t.onImgUrlFile(content);

          t.updateComponent();
          pageobj.hideLoading();
        }
      },
      function (error) {
        console.log(error);
      }
    );
    console.info("this.urls");
    console.info(this.data.urls);
  },

  onHideFiles: function () {
    this.data.gallery = update(this.data.gallery, {$set: false});
    this.updateComponent();
  },

  onDelFiles: function (index) {
    let t = this;

    var j;
    for(var i=0;i< t.data.urls.length;i++){
      if(i==index){
        j=t.data.urls[i].code;
        break;
      }
    }
    for(var i=0;i< t.data.mediaId.length;i++){
      if(null!=j)
      {
        if(t.data.mediaId[i]==j){
          t.data.mediaId.splice(i, 1);
          break;
        }
      }
    }

    this.data.urls = update(this.data.urls, {$set: this.data.urls.filter((e,i)=>i != index)});

    this.updateComponent();
  },



  showWarnMessage: function (message) {

    this.data.warnMessage = update(this.data.warnMessage, {$set: message});
    this.data.showWarn = update(this.data.showWarn, {$set: true});
    this.data.warnTimer = setTimeout(()=> {
      this.data.showWarn = update(this.data.showWarn, {$set: false});
      this.updateComponent();
    }, 3000);

    this.updateComponent();
  },

  onSetCurrentEng: function (obj) {
    let t = this;
    this.data.currentEng = update(this.data.currentEng, {$set: obj});

    this.data.jlmode = update(this.data.jlmode,{eng : {$set: obj}}  );

    this.updateComponent();
  },

  addRenYuan(obj){
    this.data.jdy.add(obj);
  },

  onSaveChange: function (obj) {
    this.data.jlmode.id = update(this.data.jlmode.id,  {$set: obj});
    this.data.isNew = update(this.data.isNew,  {$set: false});
    this.data.readOnly = false;
    this.data.operType = 'update';
    this.updateComponent();
  },

  onSaveInfo: function (obj) {
    let t = this;

    let resultEng = Utils.isEmptyObject(this.data.currentEng);
    console.info(resultEng.success);
    if (!resultEng.success)
    {
      this.showWarnMessage('工程不能为空');
      return;
    }

/*
    this.data.jlmode.jlrq =  moment(this.data.jlmode.jlrq).format('YYYY-MM-DD hh:mm:ss');
*/

    DB.WechatAPI.saveZGHFInfo(this.data.jlmode).then(
      function (content) {
        t.onSaveChange(content.code);
        t.onSaveImgFile(content.code);
      },
      function (error) {
        console.log(error);
      });
    this.updateComponent();
  },


  onUpInfo: function (obj) {
    let resultEng = Utils.isEmptyObject(this.data.currentEng);

    if (!resultEng.success)
    {
      this.showWarnMessage('工程不能为空');
      return;
    }
    let sp = {id: this.data.jlmode.id};
    console.log('id');
    console.info(sp);
    DB.WechatAPI.upZGHFInfo(sp).then(
      function (content) {

        Control.go(-1);
      },
      function (error) {
        console.log(error);
      });
    this.updateComponent();
  },

  onJlrqChange: function (params) {

    this.data.jlmode.jlrq = update(this.data.jlmode.jlrq,  {$set: params});
    this.updateComponent();
  },

  onSqRqChange: function (params) {
    this.data.jlmode.jlrq = update(this.data.jlmode.jlrq,  {$set: params});
    this.updateComponent();
  },

  onSqBlur: function (params) {
    this.data.jlmode.jlrq = update(this.data.jlmode.jlrq,  {$set: params});
    this.updateComponent();
  },

  onYjysRqChange: function (params) {

    this.data.jlmode.yjyssj = update(this.data.jlmode.yjyssj,  {$set: params});
    this.updateComponent();
  },

  onYjysBlur: function (params) {
    this.data.jlmode.yjyssj = update(this.data.jlmode.yjyssj,  {$set: params});
    this.updateComponent();
  },


  onSgjdChange: function (params) {
    this.data.jlmode.ysxmmc = update(this.data.jlmode.ysxmmc,  {$set: params});
    this.updateComponent();
  },

  onTqqkChange: function (params) {
    this.data.jlmode.tqqk = update(this.data.jlmode.tqqk,  {$set: params});
    this.updateComponent();
  },

  onCheckChange: function () {
    let zjy ='';
    if(null!= this.data.jdy && null!= this.data.jdy.length>0)
    {
      this.data.jdy.forEach(function(value,index,array){
        if (value.checked)
        {
          zjy += value.name+' ';
        }
      });
    }
    this.data.jlmode.zjy = update(this.data.jlmode.zjy,  {$set: zjy});
    this.data.jlmode.jdrys = update(this.data.jlmode.jdrys,  {$set: this.data.jdy});

    this.updateComponent();
  },

  onCheckInfo: function (obj) {
    if(null!= this.data.jdy && null!= this.data.jdy.length>0)
    {
      this.data.jdy.forEach(function(value,index,array){
        if (value.emplId == obj.target.value)
        {
          value.checked = obj.target.checked;
        }
      });
    }
    this.updateComponent();
  },



  onTqwdChange: function (params) {
    this.data.jlmode.qwqk = update(this.data.jlmode.qwqk,  {$set: params});
    this.updateComponent();
  },

  onQksgChange: function (params) {
    this.data.jlmode.sgjzqk = update(this.data.jlmode.sgjzqk,  {$set: params});
    console.info(this.data.jlmode);
    this.updateComponent();
  },

  onQkjlChange: function (params) {
    this.data.jlmode.jlgzqk = update(this.data.jlmode.jlgzqk,  {$set: params});
    console.info(this.data.jlmode);
    this.updateComponent();
  },

  onQkwtChange: function (params) {
    this.data.jlmode.czwt = update(this.data.jlmode.czwt,  {$set: params});
    console.info(this.data.jlmode);
    this.updateComponent();
  },

  onQklsChange: function (params) {
    this.data.jlmode.jlzl = update(this.data.jlmode.jlzl,  {$set: params});
    console.info(this.data.jlmode);
    this.updateComponent();
  },

  onQkqtChange: function (params) {
    this.data.jlmode.bz = update(this.data.jlmode.bz,  {$set: params});
    this.updateComponent();
  },


  //添加上传图片
  onAddImage: function (params) {
    let t = this;
    t.updateComponent();
  },


  onUpdateStore: function () {
    let t = this;
  },

  onFetch: function (params, cb) {
    let t = this;
    t.updateComponent();
    cb && cb(t.data);
  },

  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState: function () {
    return this.data;
  }


});
